<template>
  <el-card style="box-shadow: none;">
    <el-row>
      <el-tooltip class="item" effect="dark" content="返回" placement="right-start">
        <el-button type="text" @click="returnCouponsList" style="margin-left: 10px">
          <svg t="1708609271658" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
               p-id="5331" width="30" height="30">
            <path d="M257.2 567.1h584.5c29 0 52.5-23.4 52.5-52.2V512c0-28.8-23.5-52.2-52.5-52.2H255.9L431 284.1c20.2-20.3 20.2-53 0-73.3l-0.4-0.4c-20.2-20.3-53.1-20.5-73.6-0.5l-0.5 0.5L71.8 496.1a26.013 26.013 0 0 0 0 36.7l55.7 55.9L352 813.8c20.4 20.5 53.7 20.6 74.3 0.4l0.4-0.4 1.7-1.7c20.3-20.3 20.3-53.1 0-73.4L257.2 567.1z" p-id="5332" fill="#515151"></path>
          </svg>
        </el-button>
      </el-tooltip>
      <h1 class="row__title" style="margin-left: 20px;margin-top: 3px; justify-content: center;">添加优惠券</h1>
    </el-row>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
      <el-form-item label="优惠券名称：" prop="couponsName">
        <el-input v-model="ruleForm.couponsName" placeholder="请输入优惠券名称"></el-input>
      </el-form-item>
      <el-form-item label="广告主：" prop="companyName" >
        <el-select v-model="ruleForm.companyName" placeholder="请选择广告主" clearable>
          <el-option
              v-for="item in companyList"
              :key="item.advertiserId"
              :label="item.userName"
              :value="item.advertiserId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有效日期：" required prop="dateRange">
        <el-col :span="11">
          <div class="block">
            <el-date-picker
                v-model="ruleForm.dateRange"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
            </el-date-picker>
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="优惠券类型：" prop="type">
        <el-radio-group v-model="ruleForm.type">
          <el-radio-button :label="1">代金券</el-radio-button>
          <el-radio-button :label="2">满减劵</el-radio-button>
          <el-radio-button :label="3">折扣劵</el-radio-button>
          <el-radio-button :label="4">兑换券</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 1" label="代替金额：" prop="value">
        <el-input v-model="ruleForm.value" placeholder="请输入代替金额"></el-input>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 2" label="代替金额：" prop="value">
        <el-input v-model="ruleForm.value" placeholder="请输入代替金额"></el-input>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 2" label="最低消费金额：" prop="minimumAmount">
        <el-input v-model="ruleForm.minimumAmount" placeholder="请输入最低消费金额"></el-input>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 3" label="折扣比例：" prop="value1">
        <el-input-number v-model="ruleForm.value1" :precision="2" :step="0.1" :max="1" min="0" controls-position="right"></el-input-number>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 4" label="兑换商品名称：" prop="productName">
        <el-input v-model="ruleForm.productName" placeholder="请输入兑换商品名称"></el-input>
      </el-form-item>
      <el-form-item :class="{ hide: hideUpload }" v-show="ruleForm.type === 4" label="兑换商品图片：" prop="imgFileList">
        <el-upload
            ref="upload"
            action="#"
            multiple
            :limit="limit"
            :file-list="ruleForm.imgFileList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-change="OnChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            accept="image/jpeg,image/png"
            :auto-upload="false">
          <svg t="1708595840001" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
               p-id="4203" width="50" height="50"><path d="M914.618182 477.090909H546.909091V109.381818c0-18.618182-16.290909-34.909091-34.909091-34.909091s-34.909091 16.290909-34.909091 34.909091v367.709091H109.381818c-18.618182 0-34.909091 16.290909-34.909091 34.909091s16.290909 34.909091 34.909091 34.909091h367.709091v367.709091c0 18.618182 16.290909 34.909091 34.909091 34.909091s34.909091-16.290909 34.909091-34.909091V546.909091h367.709091c18.618182 0 34.909091-16.290909 34.909091-34.909091s-16.290909-34.909091-34.909091-34.909091z" fill="#8a8a8a" p-id="4204"></path></svg>
        </el-upload>
      </el-form-item>
      <el-form-item label="代金券描述：" prop="description" type="textarea">
        <el-input
              type="textarea"
              placeholder="请输入代金券描述"
              v-model="ruleForm.description"
              maxlength="150"
              show-word-limit
          >
        </el-input>
      </el-form-item>
      <el-form-item label="使用条件：" prop="condition" type="textarea">
        <el-input
            type="textarea"
            placeholder="请输入使用条件"
            v-model="ruleForm.condition"
            maxlength="100"
            show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpload()">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>


</template>
<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default{
  name: "couponMonitor",
  data() {
    return{
      ruleForm: {
        couponsName: '',
        companyName:'',
        dateRange:'',
        type:1,
        value:'',
        value1:'',
        minimumAmount: '',
        productName: '',
        description:'',
        condition: '',
        imgFileList: [],
      },
      companyList:[],
      type:1,
      rules: {
        couponsName: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: '请选择广告主', trigger: 'blur' }
        ],
        type: [
          { required: true},
        ],
        value: [
          { required: true, message: '金额不能为空' },
          { pattern: /^[0-9]+(\.[0-9]+)?$/, message: '金额必须为数字' }
        ],
        value1: [
          { required: true},
        ],
        productName: [
          { required: true, message: '请输入兑换商品名称', trigger: 'blur' }
        ],
        minimumAmount: [
          { required: true, message: '最低消费金额不能为空' },
          { pattern: /^[0-9]+(\.[0-9]+)?$/, message: '最低消费金额必须为数字' }
        ],
        imgFileList: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }

  },
  watch: {
    // 监听type变化
    'ruleForm.type': function(newVal, oldVal){
      if (newVal !==  oldVal) {
        this.resetInputForm();
      }
    },
  },
  methods: {
    returnCouponsList(){
      this.$router.push({path:'/couponManagement/CouponList'})
    },
    resetInputForm() {
      this.ruleForm = {
        couponsName: '',
        companyName:'',
        dateRange:'',
        value:'',
        minimumAmount: '',
        productName: '',
        description:'',
        condition: '',
        type:this.ruleForm.type,
        imgFileList: []
      };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    returnClothingList(){
      this.$router.push({path:'/clothesManagement/ClothesList'})
    },
    //定義新增數據
    addCouponInfo(couponsName,companyName,dateRange,type,value,minimumAmount,productName,description,condition){
      return {
        "couponsName":couponsName,"companyName":companyName, "type": type,"dateRange":dateRange,
        "value":value,"minimumAmount":minimumAmount, "productName": productName,
        "description":description,"condition":condition
      };
    },
    //点击上传图片
    submitUpload() {
      let formData = new FormData();
      let addData = this.addCouponInfo(this.ruleForm.couponsName, this.ruleForm.companyName,this.ruleForm.dateRange, this.ruleForm.type, this.ruleForm.value, this.ruleForm.minimumAmount, this.ruleForm.productName, this.ruleForm.description, this.ruleForm.condition);

      this.ruleForm.imgFileList.forEach((file) => {
        formData.append("file", file.raw);
      });

      formData.append("addData", JSON.stringify(addData)); // 将 addData 添加到 formData 中

      axios.post('/couponsManage/addCoupons', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then(response => {
            // 处理后端返回的数据
            if (response.status === 200) {
              ElMessage({
                message: '添加成功',
                type: 'success',
              });
              this.resetForm('ruleForm');
              this.ruleForm.imgFileList = [];
            }
          })
          .catch(error => {
            // 处理错误情况
            console.log(error);
            this.$message.error();
          });
    },
    //预览图片时
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      console.log("预览图片时")
    },
    OnChange(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      this.ruleForm.imgFileList.push(file);

    },
    //删除图片时
    handleRemove(file) {
      if (file.id) {
        console.log("删除了已被上传过的图片");
        console.log(file.id);
        this.deleteImgFileList.push(file.id);
      }
      // this.ruleForm.imgFileList = fileList;
      // this.hideUpload = fileList.length >= this.limit;
    },
    //文件超出个数限制时
    handleExceed() {
      this.$message.warning(
          `当前限制选择 1 个文件`
      );
    },
    handleCommodityPicSuccess(res) {
      if (res && res.code === 200) {
        this.$message.success('上传成功');
      } else if (res && res.message) {
        this.$message.error(res.message);
      } else {
        this.$message.error('上传失败，未知错误');
      }
    },
    async getCompanyList() {
      try {
        const res = await axios.get('/couponsManage/getCompanyList');

        console.log("getAttributeList返回值",res);

        if (res.status === 200) {
          this.companyList = res.data.data;
          console.log("companyList返回值",this.companyList);
        } else {
          ElMessage('获取公司数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取公司数据失败');
      }
    },
  },
  mounted() {
    this.getCompanyList();
  }

}
</script>
<style scoped>
.icon-svg:hover path {
  fill: #76cb02;
}


</style>